﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MT5Collect
{
    public class ConfigTool
    {
        ///<summary>
        /// 读取配置文件
        ///</summary>
        public static Dictionary<string, string> GetConfig(string key = "")
        {
            try
            {
                string file = System.Windows.Forms.Application.ExecutablePath;
                Configuration config = ConfigurationManager.OpenExeConfiguration(file);
                Dictionary<string, string> dic = new Dictionary<string, string>();
                if (string.IsNullOrEmpty(key))
                {
                    foreach (var item in config.AppSettings.Settings.AllKeys)
                    {
                        dic.Add(item, config.AppSettings.Settings[item].Value);
                    }
                }
                else
                {
                    string value = config.AppSettings.Settings[key].Value;
                    dic.Add(key, value);
                }
                return dic;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 保存设置
        /// </summary>
        /// <param name="dic"></param>
        public static void SaveConfig(Dictionary<string, string> dic)
        {
            try
            {
                string file = System.Windows.Forms.Application.ExecutablePath;
                Configuration config = ConfigurationManager.OpenExeConfiguration(file);
                foreach (var key in dic.Keys)
                {
                    if (config.AppSettings.Settings[key] == null)
                    {
                        config.AppSettings.Settings.Add(key, dic[key].ToString());
                    }
                    else
                    {
                        config.AppSettings.Settings[key].Value = dic[key].ToString();
                    }
                    config.Save(ConfigurationSaveMode.Modified);
                    ConfigurationManager.RefreshSection("appSettings");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}